
/**
 * @author zhouyanxiang
 * @create 2020-09-2020/9/2-12:53
 */
public class BubbleSort {

    public static void main(String[] args) {
        BubbleSort bls = new BubbleSort();
        int []arr = {26,65,93,1,25,3,56,40,31,7};
        bls.bubbleSort(arr);
        for (int num : arr){
            System.out.print(num + " ");
        }

        System.out.println();

        int []p = {15,26,30,21,61,54,50,10,96,48,77};
        bls.optimizationBubbleSort(p);
        for (int num : p){
            System.out.print(num + " " );
        }
    }

    /**
     * @param num
     *按照从小到大排序
     *交换a b也可以直接用异或
     * a = a ^ b;
     * b = b ^ a;
     * a = b ^ a;
     */
    public void bubbleSort(int[] num){
        for (int i = 0; i < num.length; i++) {
            for (int j = 0; j < num.length - 1 - i; j++) {
                if (num[j] > num[j+1]){
                    num[j] ^= num[j+1];
                    num[j+1] ^= num[j];
                    num[j] = num[j+1] ^ num[j];
                }
            }
        }
    }




    /**
     * 增加一个标志位，如果比较了一轮仍然没有发生交换，那就说明已经有序可以直接退出循环
     * @param pro
     */
    public void optimizationBubbleSort(int[] pro){
        for (int i = 0; i < pro.length; i++) {
            boolean flag = true;
            for (int j = 0; j < pro.length - 1 - i; j++) {
                if (pro[j] > pro[j+1]){
                    pro[j] ^= pro[j+1];
                    pro[j+1] ^= pro[j];
                    pro[j] = pro[j+1] ^ pro[j];
                }
                flag = false;
            }
            if (flag){
                break;
            }
        }
    }


}
